package com.gxnu.edu.cn.ttxxt.controller;

import com.gxnu.edu.cn.ttxxt.entity.Users;
import com.gxnu.edu.cn.ttxxt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/username/{username}")
    public ResponseEntity<Map<String, Object>> getUserByUsername(@PathVariable String username) {
        Map<String, Object> response = new HashMap<>();
        try {
            Users users = userService.findByUsername(username);
            if (users == null) {
                response.put("code", 404);
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", users.getUserId());
            userInfo.put("username", users.getUsername());
            userInfo.put("phone", users.getPhone());
            userInfo.put("email", users.getEmail());
            userInfo.put("avatarUrl", users.getAvatarUrl());
            userInfo.put("signature", users.getSignature());
            userInfo.put("status", users.getStatus());

            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", userInfo);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "获取用户信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @GetMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> getUserInfo(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        try {
            Users users = userService.findById(userId);
            if (users == null) {
                response.put("code", 404);
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", users.getUserId());
            userInfo.put("username", users.getUsername());
            userInfo.put("phone", users.getPhone());
            userInfo.put("email", users.getEmail());
            userInfo.put("avatarUrl", users.getAvatarUrl());
            userInfo.put("signature", users.getSignature());
            userInfo.put("status", users.getStatus());

            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", userInfo);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "获取用户信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> credentials) {
        Map<String, Object> response = new HashMap<>();
        try {
            String username = credentials.get("username");
            String password = credentials.get("password");
            String ip=credentials.get("ip");
            if (username == null || username.isEmpty()) {
                response.put("code", 400);
                response.put("message", "用户名不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            Map<String, Object> loginResponse = userService.login(username, password,ip);

            Map<String, Object> userInfo = new HashMap<>();
            Users user = (Users) loginResponse.get("user");
            userInfo.put("userId", user.getUserId());
            userInfo.put("username", user.getUsername());
            userInfo.put("avatarUrl", user.getAvatarUrl());
            userInfo.put("signature", user.getSignature());

            response.put("code", 200);
            response.put("message", "登录成功");
            response.put("data", userInfo);
            response.put("token", loginResponse.get("token"));
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            response.put("code", 401);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "登录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody Users users) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (users.getUsername() == null || users.getUsername().isEmpty()) {
                response.put("code", 400);
                response.put("message", "用户名不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            int result = userService.register(users);
            switch (result) {
                case 1:
                    response.put("code", 200);
                    response.put("message", "注册成功");
                    return ResponseEntity.ok(response);
                case 0:
                    response.put("code", 400);
                    response.put("message", "用户名已存在");
                    return ResponseEntity.badRequest().body(response);
                case -1:
                    response.put("code", 400);
                    response.put("message", "手机号已注册");
                    return ResponseEntity.badRequest().body(response);
                case -2:
                    response.put("code", 400);
                    response.put("message", "邮箱已注册");
                    return ResponseEntity.badRequest().body(response);
                default:
                    response.put("code", 500);
                    response.put("message", "注册失败");
                    return ResponseEntity.internalServerError().body(response);
            }
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @PutMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> updateUserInfo(
            @PathVariable Long userId,
            @RequestBody Users updatedUsers) {
        Map<String, Object> response = new HashMap<>();
        try {
            Users users = userService.updateUserInfo(
                    userId,
                    updatedUsers.getUsername(),
                    updatedUsers.getPhone(),
                    updatedUsers.getEmail(),
                    updatedUsers.getSignature()
            );

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", users.getUserId());
            userInfo.put("username", users.getUsername());
            userInfo.put("phone", users.getPhone());
            userInfo.put("email", users.getEmail());
            userInfo.put("avatarUrl", users.getAvatarUrl());
            userInfo.put("signature", users.getSignature());

            response.put("code", 200);
            response.put("message", "更新成功");
            response.put("data", userInfo);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            response.put("code", 400);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @PutMapping("/{userId}/password")
    public ResponseEntity<Map<String, Object>> changePassword(
            @PathVariable Long userId,
            @RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String oldPassword = request.get("oldPassword");
            String newPassword = request.get("newPassword");

            if (oldPassword == null || newPassword == null) {
                response.put("code", 400);
                response.put("message", "旧密码和新密码不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            boolean success = userService.changePassword(userId, oldPassword, newPassword);
            if (success) {
                response.put("code", 200);
                response.put("message", "密码修改成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("code", 500);
                response.put("message", "密码修改失败");
                return ResponseEntity.internalServerError().body(response);
            }
        } catch (IllegalArgumentException e) {
            response.put("code", 400);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "密码修改失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}